package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断是否缺少参数
        if(dto==null || (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //检查用户名
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(queryWrapper);

        if(one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }

        //检查密码
        //把明文+salt再md5加密  加密后再和表中的password比较
        String password_mi = DigestUtils.md5Hex(dto.getPassword() + one.getSalt());
        if (!StringUtils.equals(one.getPassword(),password_mi)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        Map resultMap = new HashMap();
        //去除one对象中的敏感数据
        one.setPassword("");
        one.setPhone("");
        one.setEmail("");
        one.setSalt("");
        resultMap.put("user",one);

        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("userId",one.getId());
        claimMaps.put("name",one.getName());
        String token = AppJwtUtil.getToken(claimMaps);

        resultMap.put("token",token);

        return ResponseResult.okResult(resultMap);
    }
}
